<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 角色列表 -->
    <el-card class="box-card">
      <el-button @click="addUserFlag = true" type="primary">添加角色</el-button>
      <!-- 用户权限列表 -->
       <template>
        <el-table
          border
          stripe
          :data="roles"
          style="width: 100%">
          <el-table-column type="expand" label="">
            <template slot-scope="scope">
              <!-- 渲染权限 -->
              <el-row class="bdbot tagCenter" :class="index === 0 ? 'bdtop' : ''" v-for="(item, index) in scope.row.children" :key="item.id">
                <!-- 渲染一级权限 -->
                <el-col :span="6"><el-tag>{{item.authName}}</el-tag><i class="el-icon-caret-right"></i></el-col>
                <!-- 渲染二级权限和三级权限-->
                <el-col :span="18">
                  <el-row class="tagCenter" :class="i === 0 ? '' : 'bdtop'" v-for="(value, i) in item.children" :key="value.id">
                    <!-- 二级权限 -->
                    <el-col :span="9">
                      <el-tag type="success">{{value.authName}}</el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <!-- 三级权限 -->
                    <el-col :span="15">
                      <el-tag @close="delTag(scope.row,val.id)" closable type="warning" v-for="val in value.children" :key="val.id">{{val.authName}}</el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column type="index" label="#"></el-table-column>
          <el-table-column prop="roleName" label="名称"></el-table-column>
          <el-table-column prop="roleDesc" label="角色"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button @click="showEditUser(scope.row)" size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
              <el-button @click="delUser(scope.row.id)" size="mini" type="danger" icon="el-icon-delete">删除</el-button>
              <el-button @click="getTreeList(scope.row)" size="mini" type="warning" icon="el-icon-setting">分配权限</el-button>
            </template>
          </el-table-column>
        </el-table>
    </template>
    </el-card>
    <!-- 编辑用户对话框 -->
    <el-dialog
      title="编辑用户"
      :visible.sync="editUserFlag"
      width="50%">
      <el-form ref="editUserForm" :model="addUserInfo" :rules="addUserRules" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addUserInfo.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addUserInfo.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editUserFlag = false">取 消</el-button>
        <el-button @click="editUser" type="primary">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加用户对话框 -->
      <el-dialog
        title="提示"
        :visible.sync="addUserFlag"
        width="50%">
        <el-form ref="addUserRef" :model="addUserInfo" :rules="addUserRules" label-width="80px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addUserInfo.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addUserInfo.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addUserFlag = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog
      @close='closeDialog'
      title="提示"
      :visible.sync="setDialogVisible"
      width="50%">
      <el-tree
      node-key="id"
      default-expand-all
      :default-checked-keys="defaultArr"
      ref="treeRef" show-checkbox :data="rights" :props="treeProps"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setEnter">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 用户列表数据
      roles: [],
      // 添加权限对话框显示字段
      setDialogVisible: false,
      // 添加用户对话框显示字段
      addUserFlag: false,
      // 渲染树形结构
      rights: [],
      // 显示树形结构数据的部分
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      // 三级权限的选中
      defaultArr: [],
      // 分配权限时的用户id
      roleId: 0,
      // 添加用户的参数
      addUserInfo: {
        roleName: '',
        roleDesc: ''
      },
      // 添加用户的规则
      addUserRules: {
        roleName: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ]
      },
      // 修改用户对话框
      editUserFlag: false,
      // 修改用户传递的每行数据临时变量
      editUserInfo: {}
    }
  },

  created () {
    this.getRoles()
  },

  methods: {
    // 获取页面角色数据
    async getRoles () {
      const { data: res } = await this.$axios.get('roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.roles = res.data
    },
    // 删除权限
    delTag (row, tagId) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$axios.delete(`roles/${row.id}/rights/${tagId}`)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        row.children = res.data
        this.$message.success('删除成功')
      }).catch(() => {
        this.$message('取消删除')
      })
    },
    // 显示分配权限
    async getTreeList (value) {
      this.roleId = value.id
      this.setDialogVisible = true
      const { data: res } = await this.$axios.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rights = res.data
      this.getArrList(value)
    },
    // 递归获取三级权限数组
    getArrList (row) {
      if (!row.children) {
        return this.defaultArr.push(row.id)
      }
      row.children.forEach(item => {
        this.getArrList(item)
      })
    },
    // 关闭添加权限对话框的回调
    closeDialog () {
      this.defaultArr = []
    },
    // 确定用户权限
    async setEnter () {
      const arr = [...this.$refs.treeRef.getHalfCheckedKeys(), ...this.$refs.treeRef.getCheckedKeys()]
      console.log(this.roleId)
      console.log(arr)
      const { data: res } = await this.$axios.post(`roles/${this.roleId}/rights`, { rids: arr.join(',') })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getRoles()
      this.setDialogVisible = false
    },
    // 添加用户
    addUser () {
      this.$refs.addUserRef.validate(async flag => {
        if (!flag) return
        const { data: res } = await this.$axios.post('roles', this.addUserInfo)
        if (res.meta.status !== 201) return this.$message.error('创建失败')
        this.$message.success(res.meta.msg)
        this.$refs.addUserRef.resetFields()
        this.addUserFlag = false
        this.getRoles()
      })
    },
    // 删除用户
    delUser (id) {
      this.$confirm('是否删除该用户数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$axios.delete(`roles/${id}`)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.getRoles()
        return this.$message.success('删除成功!')
      }).catch(() => {
        return this.$message('已取消删除')
      })
    },
    // 编辑用户对话框
    showEditUser (row) {
      this.roleId = row.id
      this.addUserInfo.roleName = row.roleName
      this.addUserInfo.roleDesc = row.roleDesc
      this.editUserInfo = row
      this.editUserFlag = true
    },
    // 确定编辑用户操作
    editUser () {
      this.$refs.editUserForm.validate(async flag => {
        if (!flag) return
        const { data: res } = await this.$axios.put('roles/' + this.roleId, this.addUserInfo)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.editUserInfo.roleName = res.data.roleName
        this.editUserInfo.roleDesc = res.data.roleDesc
        this.$refs.editUserForm.resetFields()
        this.editUserFlag = false
      })
    }
  }
}
</script>

<style scoped lang='less'>
.el-tag{
  margin: 7px;
}
.tagCenter {
  display: flex;
  align-items: center;
}
.bdbot{
  border-bottom:1px solid #eee;
}
.bdtop{
  border-top:1px solid #eee;
}
</style>
